#!/usr/bin/env python
import sys
import re
from collections import defaultdict
import os

print("{:20s}   {:10s}   {:10s}   {:<10s}".format("system","Singlet","Triplet","S1-Tn"))
warnings = []
for arg in sys.argv[1:]:
    slist,tlist = defaultdict(int),defaultdict(int)
    if os.path.isfile(arg):
        continue
    filename=os.path.join(arg,"runmrcc.out")
    try:
        
        f=open(filename,'r')
        S=re.findall(r'Singlet (excited )?states:?\n \n( Excited.*?)\n  state.*?====\n(.*?)\n ======',f.read(),re.DOTALL)
        if len(S) > 0:
            pos=S[-1][-2].strip().split().index('Excitation')
            slist = defaultdict(float,{i.split()[0]:i.split()[pos+1] for i in S[-1][-1].strip('\n').split('\n') if i.split()})
        f.seek(0)
        T=re.findall(r'Triplet (excited )?states:?\n \n( Excited.*?)\n  state.*?====\n(.*?)\n ======',f.read(),re.DOTALL)
        if len(T)>0:
            pos=T[-1][-2].strip().split().index('Excitation')
            tlist = defaultdict(float,{i.split()[0]:i.split()[pos+1]  for i in T[-1][-1].strip('\n').split('\n') if i.split()})
        sorder1='-'.join([i[0] for i in sorted(slist.items(),key=lambda x:int(x[0]))])
        sorder2='-'.join([i[0] for i in sorted(slist.items(),key=lambda x:float(x[1]))])
        order_change='' 
        if sorder1 != sorder2:
            order_change += " singlets"
            ssn=[i[0] for i in sorted(slist.items(),key=lambda x:int(x[0]))]
            sv=[i[1] for i in sorted(slist.items(),key=lambda x:float(x[1]))]
            slist= defaultdict(float,zip(ssn,sv))
        torder1='-'.join([i[0] for i in sorted(tlist.items(),key=lambda x:float(x[0]))])
        torder2='-'.join([i[0] for i in sorted(tlist.items(),key=lambda x:float(x[1]))])
        if torder1 != torder2:
            order_change += " triplets"
            tsn=[i[0] for i in sorted(tlist.items(),key=lambda x:int(x[0]))]
            tv=[i[1] for i in sorted(tlist.items(),key=lambda x:float(x[1]))]
            tlist= defaultdict(float,zip(tsn,tv))
        if order_change:
            warnings.append("{:s}: {:s} order changed".format(arg,order_change))
        f.seek(0)
        E=re.findall(r'Error at the termination of mrcc',f.read(),re.DOTALL)
        if len(E) > 0:
            slist={'1':0}
            tlist={'1':0}
    except FileNotFoundError:
        slist={'1':0}
        tlist={'1':0}
    for i in range(max(len(slist),len(tlist))):
        idx=str(i+1)
        if(float(tlist[idx])==0 or float(slist["1"]) == 0):
            dst=0
        else:
            dst=float(slist["1"])-float(tlist[idx])
        print("{:20s}   {:10s}   {:10s}   {:<10.4f}".
              format(arg,"S"+idx+": "+str(slist[idx]),"T"+idx+": "+str(tlist[idx]),dst))
for w in warnings:
    print(w)
        
            

